package com.lemobar.pay.service.impl.wx;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;


/**
 * 微信签名工具类
 * 验签工具类
 */
public class WxPaySignature {
    /**
     * 签名（MD5签名）
     * 微信小程序支付-签名 https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=4_3
     * @param params
     * @param signKey
     * @return
     */
    public static String sign(Map<String, String> params, String signKey) {
        /*
        SortedMap<String, String> sortedMap = new TreeMap<>(params);

        StringBuilder toSign = new StringBuilder();
        for (String key : sortedMap.keySet()) {
            String value = params.get(key);
            if (StringUtils.isNotEmpty(value) && !"sign".equals(key) && !"key".equals(key)) {
                toSign.append(key).append("=").append(value).append("&");
            }
        }

        toSign.append("key=").append(signKey);
        return DigestUtils.md5Hex(toSign.toString()).toUpperCase();
        */
        return sign(params, "MD5", signKey);
    }

    /**
     * 生成sign HMAC-SHA256 或 MD5 签名
     * 微信小程序支付-签名 https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=4_3
     * @param params
     * @param signType HMAC-SHA256 或 MD5
     * @param signKey
     * @return sign
     */
    public static String sign(Map<String, String> params, String signType, String signKey) {
        SortedMap<String, String> sortedMap = new TreeMap<>(params);

        StringBuilder toSign = new StringBuilder();
        for (String key : sortedMap.keySet()) {
            String value = params.get(key);
            if (StringUtils.isNotEmpty(value) && !"sign".equals(key) && !"key".equals(key)) {
                toSign.append(key).append("=").append(value).append("&");
            }
        }
        toSign.append("key=").append(signKey);
        if("HMAC-SHA256".equalsIgnoreCase(signType)){
            try {
                Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
                SecretKeySpec secret_key = new SecretKeySpec(signKey.getBytes("UTF-8"), "HmacSHA256");
                sha256_HMAC.init(secret_key);
                return Hex.encodeHexString(sha256_HMAC.doFinal((toSign.toString()).getBytes("UTF-8"))).toUpperCase();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }else{ //default MD5
            return DigestUtils.md5Hex(toSign.toString()).toUpperCase();
        }

    }

    /**
     * 签名for App
     * 微信APP - 签名 https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=4_3
     * @param params
     * @param signKey
     * @return
     */
    public static String signForApp(Map<String, String> params, String signKey) {
        SortedMap<String, String> sortedMap = new TreeMap<>(params);

        StringBuilder toSign = new StringBuilder();
        for (String key : sortedMap.keySet()) {
            String value = params.get(key);
            if (StringUtils.isNotEmpty(value) && !"sign".equals(key) && !"key".equals(key)) {
                toSign.append(key.toLowerCase()).append("=").append(value).append("&");
            }
        }

        toSign.append("key=").append(signKey);
        return DigestUtils.md5Hex(toSign.toString()).toUpperCase();
    }

    /**
     * 校验签名
     * 支付回调使用
     * @param params
     * @param privateKey
     * @return
     */
    public static Boolean verify(Map<String, String> params,  String privateKey) {
        String sign = sign(params, privateKey);
        return sign.equals(params.get("sign"));
    }
}
